package com.kisyou.blogs;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class 发表文章 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);

        System.out.print("用户名: ");
        String author = scanner.nextLine();

        System.out.print("标题: ");
        String title = scanner.nextLine();

        System.out.print("正文: ");
        String content = scanner.nextLine();

        /**
         * 获取当前时间，并将其按照我们规定的格式转为String类型
         */
        ZoneId zone = ZoneId.of("Asia/Shanghai");
        LocalDateTime now = LocalDateTime.now(zone);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//HH 大写H为24小时制
        String publishedAt = now.format(formatter);

        String sql = "insert into blogs (author, title, published_at, content) values (?, ?, ?, ?)";

        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                // 1. 进行动态绑定
                ps.setString(1, author);
                ps.setString(2, title);
                ps.setString(3, publishedAt);
                ps.setString(4, content);

                // 此处是不带结果集的查询
                System.out.println(ps);
                ps.executeUpdate();

                System.out.println("文章发表成功");
            }
        }
    }
}
